package com.limf.demo.dao;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.limf.demo.util.CommonUtil;

public class TableDao {

	public static void generateTableDao(String fileName, String dataFile) {

		// 创建临时文件夹
		int index1 = dataFile.lastIndexOf("/");
		String folder = dataFile.substring(0, index1) + "/tmp";
		File file1_fd = new File(folder);
		if (!file1_fd.exists()) {
			file1_fd.mkdir();
		}

		// 创建文件
		String jb1 = folder + "/I" + StringUtils.capitalize(CommonUtil.convertString(fileName)) + "Dao.java";
		File jb1_file = new File(jb1);
		if (jb1_file.exists()) {
			jb1_file.delete();
		}
		try {
			jb1_file.createNewFile();

			// 写文件数据
			String data_struct = convertJB_struct(fileName);
			String dataDefine = convertData(fileName);
			FileWriter fileWritter = new FileWriter(jb1, true);
			fileWritter.write(data_struct.substring(0, data_struct.lastIndexOf("}")));
			fileWritter.write(dataDefine);
			fileWritter.write("}");

			fileWritter.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 转换字符串，数据字段与对象属性的转换
	 */
	public static String convertData(String fileName) {

		StringBuilder sbn = new StringBuilder();
		String objName = StringUtils.capitalize(CommonUtil.convertString(fileName));

		sbn.append("\n/**查询列表\n* @return \n* @throws Exception \n */");
		sbn.append("\npublic List queryList() throws Exception;\n");

		sbn.append("\n/**查询列表(分页)\n* @return \n* @throws Exception \n */");
		sbn.append("\npublic List queryList_page(Page page) throws Exception;\n");

		sbn.append("\npublic int getTotal() throws Exception;\n");
		sbn.append("\n/**\n*添加对象\n* @param ab \n* @throws Exception \n */");
		sbn.append("\npublic void insert" + objName + "(" + objName + " ab) throws Exception;\n");

		sbn.append("\n/***获取对象 * @throws Exception  */");
		sbn.append("\npublic " + objName + " query" + objName + "(int id) throws Exception;\n");

		sbn.append("\n/**修改对象* @param ab * @throws Exception \n */");
		sbn.append("\npublic void update" + objName + "(" + objName + " sr) throws Exception;\n");

		sbn.append("\n/**删除对象 \n* @throws Exception \n */");
		sbn.append("\npublic void delete" + objName + "(int id) throws Exception;\n");

		return sbn.toString();
	}

	/**
	 * 生成Dao接口的外部框代码内容
	 * 
	 * @param fileName
	 * @return
	 */
	public static String convertJB_struct(String fileName) {
		StringBuilder sb_str = new StringBuilder();
		fileName = StringUtils.capitalize(CommonUtil.convertString(fileName));
		sb_str.append("\rpublic interface I" + fileName + "Dao{}");

		System.out.println("\rpublic interface I" + fileName + "Dao{}");
		return sb_str.toString();
	}

	public String getDaoDM(String tableName, String fileName) {

		return "";
	}

	public static void main(String[] args) {
		// 生成TableDao接口文件
		generateTableDao("share_resource", "D:/项目资料/java/data.txt");
	}

}
